ThreadingMixIn和ForkingMixIn类

Python的SocketServer模块提供ThreadingMixIn和ForkingMixIn类来实现异步处理,分别通过多线程和多进程支持并发。文章通过示例介绍了如何结合这些类创建多线程或多进程的TCP和UDP服务器,并强调了在处理请求时的注意事项,如请求处理类的handle方法和异步模型的选择。
摘要由CSDN通过智能技术生成

异步混合:

为了建立异步处理机制,需要使用ThreadingMixIn和ForkingMixIn类。

以下是一个使用ThreadingMixIn类的示例:

<strong>import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver</strong><span style="color:#cc0000;">.BaseRequestHandler):
</span>
   <span style="color:#ff0000;"> def handle(self):
</span><strong>        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("{}: {}".format(</strong><span style="color:#ff0000;">cur_thread.name, data</span><strong>), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn,</strong> <span style="color:#ff0000;"><strong>socketserver.TCPServer):</strong>
</span><strong>    pass

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    try:
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: {}".format(response))
    finally:
        sock.close()

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0</strong>

    <span style="color:#ff0000;">server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
</span><span style="color:#ff0000;">    ip, port = server.server_address
</span><strong>
    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(</strong><span style="color:#ff0000;">target=server.serve_forever</span><strong>)
    # Exit the server thread when the main thread terminates</strong>
    <span style="color:#ff0000;">server_thread.daemon = True
    server_thread.start()
</span><strong>    print("Server loop running in thread:", server_thread.name)</strong>

    <span style="color:#ff0000;">client(ip, port, "Hello World 1")
    client(ip, port, "Hello World 2")
    client(ip
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值